import {
  fetchOrders
} from "../../api/order"
Page({
  page: {
    size: 5,
    num: 1,
  },
  data: {
    orderList: [],
    listLoading: 0,
    cartGroupData: null,
    pullDownRefreshing: false,
  },

  // 调用自定义tabbar的init函数，使页面与tabbar激活状态保持一致
  onShow() {
    this.getTabBar().init();
    this.getOrderList(2);
  },

  onLoad() {
    this.refreshData();
  },

  refreshData() {
    this.setData({
      orderList: []
    });
    this.getOrderList(2)
  },
  // 注：实际场景时应该调用接口获取购物车数据

  getOrderList(statusCode = -1, reset = false) {
    const params = {
      pageSize: this.page.size,
      pageNum: this.page.num,
    };
    if (statusCode !== -1) params.status = statusCode;
    this.setData({
      listLoading: 1,
      orderList: []
    });
    return fetchOrders(params)
      .then((res) => {
        this.page.num++;
        let orderList = [];
        if (res && res.data && res.data.data) {
          orderList = (res.data.data || []).map((order) => {
            return {
              id: order.orderId,
              orderNo: order.orderNo,
              status: order.orderStatus,
              statusDesc: order.orderStatusName,
              amount: order.amount,
              createTime: order.createTime,
              goods: order.goodsInfo
            };
          });
        }
        return new Promise((resolve) => {
          if (reset) {
            this.setData({
              orderList: []
            }, () => resolve());
          } else resolve();
        }).then(() => {
          this.setData({
            orderList: this.data.orderList.concat(orderList),
            listLoading: orderList.length > 0 ? 0 : 2,
          });
        });
      })
      .catch((err) => {
        this.setData({
          listLoading: 3
        });
        return Promise.reject(err);
      });
  },
});